<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/16
 * Time: 21:04
 */

namespace app\index\controller;


use app\admin\model\GoodsModel;
use app\index\lib\Wxrefund;
use app\lib\SendTemplate;
use think\Db;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
class Order
{
    //生成订单
    public function setorder(){
        $param = input();
        $order_mun = date('YmdHis',time()).rand(1000,10000);
        //查询地址
        $addr = Db::name('addr')->alias('a')
            ->join('area b','a.sheng = b.id')
            ->join('area c','a.shi = c.id')
            ->join('area d','a.xian = d.id')
            ->where('a.addr_id',$param['addr_id'])
            ->field('a.*,b.name as bname,c.name as cname, d.name as dname')
            ->find();
        //如果是立即购买
        if (isset($param['goodsid'])){
            $shop_price = 0;
            $shuxing_name = '';
            $goodscardata = db('goods')->where('id',$param['goodsid'])->select();
            $shop_price = $goodscardata[0]['shop_price'];
            if (input('shuxingid')){
                $shuxin = db('shuxing')->where('id',input('shuxingid'))->find();
                $shop_price = $shuxin['price'];
                $shuxing_name = $shuxin['name'];
            }

            foreach ($goodscardata as $v){
                $re = [
                    'order_mun'      => $order_mun,
                    'goods_name'     =>$v['goods_name'],
                    'remark'         =>$param['remark'],
                    'servcietime'    =>strtotime($param['date']),
                    'price'          =>$shop_price,
                    'munber'         =>$param['mun'],
                    'addr'           =>$addr['bname'].'/'.$addr['cname'].'/'.$addr['dname'].'/'.$addr['xiangxi'],
                    'name'           =>$addr['addr_name'],
                    'phone'          =>$addr['phone'],
                    'province'       =>$addr['sheng'],
                    'city'           =>$addr['shi'],
                    'county'         =>$addr['xian'],
                    'addtime'        =>time(),
                    'memberid'       =>$param['userid'],
                    'type'           =>$param['type'],
                    'img'            =>$param['img'],
                    'shuxing_name'      =>$shuxing_name,
                    'goods_img'      =>$v['original_img'],
                    'fenlei_id'      =>$v['cat_id'],
                ];
            }
            $resid = db('orders')->insertGetId($re);
        }else{
            //如果是购物车
            $where = ['unionid'=>$param['unionid'],'is_select'=>1];
            $goodscardata = Db::name('goodscar')->where($where)->select();
            foreach ($goodscardata as $v){
                $goods = db('goods')->where('id',$v['goods_id'])->find();
                $shuxing_name = '';
                if (!empty($v['shuxing_id'])){
                    $res = db('shuxing')->where('id',$v['shuxing_id'])->find();
                    $price = $res['price'];
                    $shuxing_name = $res['name'];
                }else{
                    $price = $goods['shop_price'];
                }
                $re = [
                    'order_mun'   => $order_mun,
                    'goods_name'  =>GoodsModel::get($v['goods_id'])['goods_name'],
                    'remark'      =>$param['remark'],
                    'servcietime' =>strtotime($param['date']),
                    'price'       =>$price,
                    'munber'      =>$v['goodsmun'],
                    'addr'        =>$addr['bname'].'/'.$addr['cname'].'/'.$addr['dname'].'/'.$addr['xiangxi'],
                    'name'        =>$addr['addr_name'],
                    'phone'       =>$addr['phone'],
                    'province'       =>$addr['sheng'],
                    'city'           =>$addr['shi'],
                    'county'         =>$addr['xian'],
                    'addtime'     =>time(),
                    'memberid'    =>$param['userid'],
                    'type'        =>$param['type'],
                    'img'         =>!empty($param['img'])!= true?implode(',',$param['img']):'',
                    'shuxing_name'   =>$shuxing_name,
                    'goods_img'   =>$goods['original_img'],
                    'fenlei_id'   =>$goods['cat_id'],
                ];
            }
            $resid = db('orders')->insertGetId($re);
            //更新购物车状态
            Db::name('goodscar')->where($where)->update(['is_select'=>2]);
        }
        if ($resid){
            return json(msg(1, ['order_mun'=>$order_mun], '添加成功'));
        }else{
            return json(msg(-1, '', '未知错误'));
        }
    }
    //支付回调
    public function notify(){
        $param = input();
        if ($param['type'] == 1){
            //商城订单
            db('orders')->where('order_mun',$param['order_mun'])->update(['status'=>2,'a_time'=>time()]);
//
            (new SendTemplate($param['order_mun']))->toDoSend(1);
            return json(msg(1, [], '支付成功'));
//            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        }elseif ($param['type'] == 'weikuan'){
            db('orders')->where('id',$param['order_mun'])->update(['status'=>4]);//更新订单状态为完成
            db('member')->where('id',$param['userid'])->setDec('count');//修改接单次数
            $data = ['type'=>4, 'member_id'=>$param['userid'], 'addtime'=>time(),'remake'=>'订单:'.$param['order_mun'], 'money'=>$param['price']];
            qianbao($param['price'],$param['order_mun']);
            if (isset($param['couponid']) && !empty($param['couponid'])){
                //如果使用优惠券
                $coupon = db('coupon_h')->where('coupon_id',$param['couponid'])->find();
                db('orders')->where('order_mun',$param['order_mun'])->update(['coupon_id'=>$param['couponid'],'coupon_price'=>$coupon['price']]);
                db('coupon_h')->where('coupon_id',$param['couponid'])->update(['status'=>2, 'order_mun'=>$param['order_mun']]);
            }
            if (isset($param['dianzan_status']) && !empty($param['dianzan_status'])){
                //如果有使用点赞
                db('orders')->where('order_mun',$param['order_mun'])->update(['isok_price'=>$param['dianzan_status']]);
                db('dianzan')->where('userid',$param['userid'])->update(['status'=>2,'order_mun'=>$param['order_mun']]);
            }
            //添加支付记录表
            $resid = db('money')->insertGetId($data);
            if ($resid){

                return json(msg(1, [], '支付成功'));
            }else{
                return json(msg(-1, '', '未知错误'));
            }
//            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        }elseif ($param['type'] == 'chongzhi'){
            $data = ['type'=>3, 'member_id'=>$param['userid'], 'addtime'=>time(),'remake'=>'充值', 'money'=>$param['chongzhi']];
            db('money')->insertGetId($data);
            $money = db('member')->where('id',$param['userid'])->field('cz_yue')->find();
            if ($param['chongzhi'] ==10 ){
                $total = $param['chongzhi']+1;
            }elseif ($param['chongzhi'] ==100 ){
                $total = $param['chongzhi']+5;
            }
            $updata=['cz_yue'=>$money['cz_yue']+$total];
            $resid = db('member')->where('id',$param['userid'])->update($updata);
            #########添加钱包记录
            $maxdata = db('congzhi')->where('userid',$param['userid'])->order('id desc')->limit(1)->select();
            $ticheng['userid'] = $param['userid'];
            $ticheng['type'] = 1;
            $ticheng['ticheng'] = 1;
            $ticheng['remark'] = '充值';
            $ticheng['money'] = $total;
            $ticheng['addtime'] = time();
            $ticheng['after'] = $maxdata[0]['after'] + $total;//求改变后的量
//            db('ticheng')->insertGetId($ticheng);
            //更新充值表
            db('congzhi')->insertGetId($ticheng);
            if ($resid){

                return json(msg(1, [], '支付成功'));
            }else{
                return json(msg(-1, '', '未知错误'));
            }
//            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        }
    }


    //订单列表
    public function getorderList(){
        $input = input();
        $where = [];
        $where['type'] = $input['type'];
        $where['memberid'] =$input['id'];
        if (isset($input['status'] ) && $input['status'] != 'all'){
            $where['status'] = $input['status'];
        }
        if(isset($input['orderid'])){
            $where['orderid'] = $input['orderid'];
        }

        $data = db('orders') ->field('order_mun,id,status,munber,price,goods_name,(IFNULL(goods_img,"")) as original_img,genhuan_status')
                            ->where($where)
                            ->order('id desc')
                            ->paginate(10);

        $data1 =  $data->toArray();
        unset($data);
        $arr = $data1['data'];
        $newarr = $newarr1 = [];
        if ($arr){
            foreach($arr as $k => $item) {
                $newarr[$item['order_mun']]['order_mun'] = $item['order_mun'];
                $newarr[$item['order_mun']]['id'] = $item['id'];
                $newarr[$item['order_mun']]['status'] = $item['status'];
                $newarr[$item['order_mun']]['countnum'] = $item['munber'];
                $newarr[$item['order_mun']]['genhuan_status'] = $item['genhuan_status'];
//                $newarr[$item['order_mun']]['order_amount'] = $item['munber'] * $item['price']+ $item['munber'] * $item['price'];
                $newarr[$item['order_mun']]['order_amount'] = $item['price'];
                $newarr[$item['order_mun']]['items'][] = $item;
            }


            unset($arr);
            $i = 0;
            foreach ($newarr as $value){
                $newarr1[$i] = $value;
                ++$i;
            }
            unset($newarr);
            $data1['data'] = $newarr1;
            $falg = msg(1, $data1,'ok');
        }else{
            $falg = msg(-1, [],'失败');
        }

        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    /**
     * 更换师傅
     * @return array
     */
    public function genhuanshifu(){
        $order_mun = input('order_mun');
        $quxiao_remake = input('quxiao_remake');
        $order = db('orders')->where('order_mun',$order_mun)->find();
        //如果还可以更换
        if ($order['genhuan_status'] == 1){

            $data['quxiao_remake'] = $quxiao_remake;
            $data['order_mun'] = $order_mun;
            $data['type'] = 3;
            $data['addtime'] = time();
            db('quxiaoorder')->insertGetId($data);

            //判断是否有人维修
            $weixiou = db('weixiou')->where(['orderid'=>$order_mun,'type'=>1])->find();
            $wxopenid = '';
            if (!empty($weixiou)){
                db('weixiou')->where(['orderid'=>$order_mun])->update(['type'=>4]);
                $user = db('member')->where('id',$weixiou['userid'])->find();
                $wxopenid = $user['wxopenid'];
                db('weixiou')->where(['orderid'=>$order_mun])->update(['type'=>4]);
                //发送模板信息通知接单人
                (new SendTemplate($order_mun,[],0,false))->toDoSend(2,$user['wxopenid']);
            }
            //重新推送订单
            (new SendTemplate($order_mun))->toDoSend(1,$wxopenid);

            $re = db('orders')->where('order_mun',$order_mun)->update(['genhuan_status'=>2]);
            if ($re){
                return json(msg(1,[],'更换成功'));
            }else{
                return json(msg(-1,[],'更换失败'));
            }
        }else{
            return json(msg(-1,[],'您已不能再跟换师傅'));
        }
    }

    /**
     * 获取取消或更换师傅原因
     */
    public function getquxiao(){
        $data = \db('config')->where('id',1)->find();
        $re['yh_quxiao'] = !empty($data['yh_quxiao'])?explode(',',$data['yh_quxiao']):[];
        $re['genhuan_remake'] = !empty($data['genhuan_remake'])?explode(',',$data['genhuan_remake']):[];
        return json($re);
    }

    /**
     *退款
     */
    public function tuikuanorder(){
        $order_mun = input('order_mun');
        $quxiao_remake = input('quxiao_remake');
        $quxiao_type = 1;
        $quxiao_time = time();
        $status = 6;
        db('orders')->where('order_mun',$order_mun)->update(compact('quxiao_remake','quxiao_type','quxiao_time','status'));
        //添加退款原因
        $data['quxiao_remake'] = $quxiao_remake;
        $data['order_mun'] = $order_mun;
        $data['type'] = 4;
        $data['addtime'] = time();
        db('quxiaoorder')->insertGetId($data);
        //申请退款
        $order = db('orders')->where('order_mun',$order_mun)->find();
        $toatle = $this->getTotalPrice($order_mun);
        $user = Db::name('member')->where('id',$order['memberid'])->find();
        $wechat =  new Wxrefund($user['xcxopenid'],$order['out_trade_no'],$toatle,$order['order_mun'],$toatle);
        $re = $wechat->refund();
        $f = fopen('tui.txt','a+');
        fwrite($f,json_encode($re));
        fclose($f);
        //判断是否有人维修
        $weixiou = db('weixiou')->where(['orderid'=>$order_mun,'type'=>1])->find();
        $wxopenid = '';
        if (!empty($weixiou)){
            $user = db('member')->where('id',$weixiou['userid'])->find();
            $wxopenid = $user['wxopenid'];
            db('weixiou')->where(['orderid'=>$order_mun])->update(['type'=>4]);
            //发送模板信息通知接单人
            (new SendTemplate($order_mun,[],0,false))->toDoSend(2,$user['wxopenid'],2);
        }
        (new SendTemplate($order_mun))->toDoSend(1,$wxopenid);
        return  json(msg(1,[],'申请成功'));
    }

    public function getTotalPrice($order_mun){
        $order = Db::name('orders')->where('order_mun',$order_mun)->select();
        $toatle = 0;
        foreach ($order as $v){
            $toatle += $v['munber'] * $v['price'];
        }
        return $toatle * 100;
    }


    // 上传缩略图
    public function uploadImg()
    {
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
        if($info){
            $src =  '/upload' . '/' . date('Ymd') . '/' . $info->getFilename();
            $falg = msg(1, ['src'=>$src],'ok');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        }else{
            // 上传失败获取错误信息
            $falg = msg(1, [],'ok');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        }
    }

    public function getmenu(){
        $menu = Db::name('fenlei')->where('pid',0)->field('id,name')->select();
        foreach ($menu as $v){
            $goods[] = Db::name('goods')->where('cat_id',$v['id'])->field('id,goods_name')->select();
        }
        $goods1=[];
        foreach ($goods as $k => $v){
            if (!empty($v)){
                $goods1[$k] = array_column($v,'goods_name');
            }else{
                $goods1[$k] =[];
            }
        }
        $return['menu'] = array_column($menu,'name');
        $return['goods'] = $goods;
        $return['goods1'] = $goods1;
        $falg = msg(1, $return,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        die;

    }
    //维修清单
    public function getweixiouh(){
//        $weixiouid = db('weixiou')->where('orderid',input('order_mun'))->find();
        $data = db('weixiou_j')->where('orderid',input('order_mun'))->find();

        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        die;
    }

    /**
     *提交评论
     */
    public function pinglun(){
        $param = input();
        db('orders')->where('order_mun',$param['order_mun'])->update(['pinglun'=>$param['pinlun'],'pinglun_time'=>time(),'status'=>5,'hzc' => $param['selecet']]);
    }

    public function getpinglun(){
        $param = input();
        $data = db('orders')->where('order_mun',$param['order_mun'])->find();
        $falg = msg(1, ['data'=>$data],'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }


}